package scanpackage.inbound;


import com.alibaba.fastjson.JSON;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.util.ReferenceCountUtil;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import scanpackage.outbound.HttpOutboundHandler;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import java.util.UUID;
import java.util.concurrent.locks.LockSupport;

import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

@ChannelHandler.Sharable
@Service
public class HttpInboundHandler extends ChannelInboundHandlerAdapter {
    @Autowired
    private HttpOutboundHandler handler;
    @Autowired
    private JmsTemplate jmsTemplate;
    @Autowired
    private CacheManager cacheManager;

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {

            FullHttpRequest fullRequest = (FullHttpRequest) msg;


            //如果3秒没拿到结果就证明后端访问有问题
            handlerTest(fullRequest, ctx);
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    private  void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
        FullHttpResponse response = null;
        //使用uuid作为该线程的识别代码
        String uuid= UUID.randomUUID().toString();
        jmsTemplate.send("sendback", new MessageCreator() {

            public Message createMessage(Session session) throws JMSException {
                return session.createObjectMessage(JSON.toJSONString(uuid));
            }
        });
        Cache cache = cacheManager.getCache("cacheTest");


        try {
//            String value = HttpClient.contact();
            String value= "hello";
            while (true)
            {
                final Element getGreeting = cache.get(uuid);
                if(getGreeting!=null) {
                    value=getGreeting.getObjectValue().toString();
                    break;
                }
            }
            response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
            response.headers().set("Content-Type", "application/json");
            response.headers().setInt("Content-Length", response.content().readableBytes());

        } catch (Exception e) {
            System.out.println("处理出错:"+e.getMessage());
            response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
        } finally {
            if (fullRequest != null) {
                if (!HttpUtil.isKeepAlive(fullRequest)) {
                    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
                } else {
//                    response.headers().set(CONNECTION, KEEP_ALIVE);
                    ctx.write(response);
                }
            }
        }
    }



}
